package com.weixin.project.Service;

import com.weixin.project.Common.Enum.EntityType;
import com.weixin.project.Common.Enum.UndoType;
import com.weixin.project.Dao.*;
import com.weixin.project.Entity.Answer;
import com.weixin.project.Entity.Chapter;
import com.weixin.project.Entity.UndoLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class UndoService {
    @Autowired
    UndoDao undoDao;
    @Autowired
    AnswerDao answerDao;
    @Autowired
    QuestionDao questionDao;
    @Autowired
    ChapterDao chapterDao;
    @Autowired
    QuestionBankDao questionBankDao;
    @Autowired
    PracticeHistoryDao practiceHistoryDao;
    public void addUndoLog(EntityType entityType, Integer entityId,
                           UndoType undoType, String uuid){
        UndoLog undoLog = new UndoLog();
        undoLog.setCreateTime(new Date());
        undoLog.setEntityId(entityId);
        undoLog.setEntityName(entityType);
        undoLog.setUndoType(undoType);
        undoLog.setUuid(uuid);
        undoDao.save(undoLog);
    }

    @Transactional
    public void undo(String uuid){
        List<UndoLog> undoLogs = undoDao.getUndoLogsByUuid(uuid);
        for(UndoLog undoLog:undoLogs){
            //对于导入题库而言，应该只有delete一种类型
            if (undoLog.getUndoType().equals(UndoType.DELETE)){
                deleteUndo(undoLog);
            }
        }
        undoDao.deleteUndoLogsByUuid(uuid);
    }

    /**
     * 这个方法不是用来在数据库中删除undoLog!!!而是用来执行类型为删除的撤销操作
     * @param undoLog
     */
    private void deleteUndo(UndoLog undoLog){
        switch (undoLog.getEntityName()){
            case ANSWER: {
                Integer answerId = undoLog.getEntityId();
                answerDao.deleteById(answerId);
                break;
            }
            case QUESTION: {
                Integer questionId = undoLog.getEntityId();
                practiceHistoryDao.deletePracticeHistoriesByQuestionId(questionId);
                //TODO:需要级联删除的不只是刷题记录
                questionDao.deleteById(questionId);
                break;
            }
            case CHAPTER: {
                Integer chapterId = undoLog.getEntityId();
                chapterDao.deleteById(chapterId);
                break;
            }
            case QUESTION_BANK: {
                Integer bankId = undoLog.getEntityId();
                questionBankDao.deleteById(bankId);
                break;
            }
        }
    }
}
